package net.asciiworks.filesyncr.model {
    import net.asciiworks.filesyncr.ApplicationFacade;

    import flash.events.StorageVolumeChangeEvent;
    import flash.filesystem.StorageVolume;
    import flash.filesystem.StorageVolumeInfo;

    import mx.collections.ArrayCollection;

    import org.puremvc.as3.interfaces.IProxy;
    import org.puremvc.as3.patterns.proxy.Proxy;

    public class VolumeProxy extends Proxy implements IProxy {
        public static const NAME:String = "VolumeProxy";

        public var volumes:ArrayCollection;

        public function VolumeProxy() {
            super(NAME, data);
            StorageVolumeInfo.storageVolumeInfo.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT, storageVolumeMountHandler);
            StorageVolumeInfo.storageVolumeInfo.addEventListener(StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT, storageVolumeUnmountHandler);
            retrieveCurrentVolumes();
            sendNotification(ApplicationFacade.VOLUMES_CHANGED, volumes);
        }

        private function storageVolumeMountHandler(event:StorageVolumeChangeEvent):void {
            if (event.storageVolume.isRemovable)
                volumes.addItem(event.storageVolume);
        }

        private function storageVolumeUnmountHandler(event:StorageVolumeChangeEvent):void {
            var retrievedVolumes:Vector.<StorageVolume> = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();

            var volumeExists:Function = function(item:StorageVolume, index:int, vector:Vector.<StorageVolume>):Boolean {
                    return this.rootDirectory.url == item.rootDirectory.url;
                }

            for each (var vol:StorageVolume in volumes) {
                if (!retrievedVolumes.some(volumeExists, vol))
                    volumes.removeItemAt(volumes.getItemIndex(vol));
            }
        }

        private function retrieveCurrentVolumes():void {
            var retrievedVolumes:Vector.<StorageVolume> = StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
            volumes = new ArrayCollection();
            for each (var vol:StorageVolume in retrievedVolumes) {
//                if (vol.isRemovable)
                    volumes.addItem(vol);
            }
        }
    }
}